//
//  TestViewController.m
//  Cartest
//
//  Created by wkf on 14/11/26.
//  Copyright (c) 2014年 wkf. All rights reserved.
//

#import "TestViewController.h"
#define ORIGINAL_MAX_WIDTH 640.0f

static NSString * const kLanguage = @"chi_sim";

@interface TestViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIActionSheetDelegate,VPImageCropperDelegate>
{
    UIImageView *imageView;
    SACameraPickerViewController *imagePicker;
    UILabel *contenLab;
}


@end

@implementation TestViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    imagePicker = [[UIImagePickerController alloc] init];
//    imagePicker.view.frame = CGRectMake(0, 200, 320, 60);
//    imagePicker.view.backgroundColor = [UIColor redColor];
//    [imagePicker setAllowsEditing:YES];
    imagePicker = [[SACameraPickerViewController alloc] initWithCameraPickerViewControllerMode:SACameraPickerViewControllerModeNormal];

    UIImage *image = [UIImage imageNamed:@"car2.png"];
    imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 20, 300, 200)];
    imageView.layer.borderColor = [[UIColor redColor]CGColor];
    imageView.image = image;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:imageView];
    
    contenLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 250, 320, 100)];
    contenLab.numberOfLines = 0;
    contenLab.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:contenLab];

    UIButton *photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    photoBtn.frame = CGRectMake(100, 400, 160, 50);
    photoBtn.backgroundColor = RGBCOLOR(1, 1, 230);
    //[UIColor colorWithRed:0/255.0f green:191/255.0f blue:255/255.0f alpha:1];//colorWithRed:0.75 green:0.75 blue:0.75];
    photoBtn.userInteractionEnabled = YES;
    [photoBtn setTitle:@"拍照" forState:UIControlStateNormal];
    [photoBtn addTarget:self action:@selector(changeHeadImage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:photoBtn];
    
//    [self analyze:image];
}

- (void)analyze :(UIImage *)image
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    
        CIImage *ciImage = [[CIImage alloc] initWithImage:imageView.image];
        
        //文字を読みやすくするため、白黒にして、コントラストを強めに、また輪郭をくっきりさせるよう設定する
//        颜色
//        CIColorMonochrome : 黑白照
        
        CIFilter *filter =
//        [CIFilter filterWithName:@"CIColorMonochrome"
//                   keysAndValues:kCIInputImageKey, ciImage,
//         @"inputColor", [CIColor colorWithRed:0 green:0 blue:0],
//         @"inputIntensity", [NSNumber numberWithFloat:1],
//         nil];
        
//        二值化
/*
    inputSaturation : 饱和度
    inputBrightness : 亮度
    inputContrast   : 对比度
 
 */
        
        
//        锐化
//        ciFilter =
        [CIFilter filterWithName:@"CIColorControls"
                           keysAndValues:kCIInputImageKey, ciImage,
                 @"inputSaturation", [NSNumber numberWithFloat:1.0],
                 @"inputBrightness", [NSNumber numberWithFloat:0.1],
                 @"inputContrast", [NSNumber numberWithFloat:7.0],
                 nil];

        
        filter = [CIFilter filterWithName:@"CIUnsharpMask"
                   keysAndValues:kCIInputImageKey, [filter outputImage],
         @"inputRadius", [NSNumber numberWithFloat:5],
         @"inputIntensity", [NSNumber numberWithFloat:0.5],
         nil];
        
    
        
        filter = [CIFilter filterWithName:@"CIColorMonochrome"
                            keysAndValues:kCIInputImageKey, [filter outputImage],
                  @"inputColor", [CIColor colorWithRed:0.8 green:0.8 blue:0.8],
                  @"inputIntensity", [NSNumber numberWithFloat:1],
                  nil];
        
//        高斯
//        [CIFilter filterWithName:@"CIGaussianBlur" keysAndValues:kCIInputImageKey, ciImage, @"inputRadius", [NSNumber numberWithFloat:2], nil];
        
        // blur image
        CIContext *ciContext = [CIContext contextWithOptions:nil];
        CIImage *result = [filter outputImage];//[CIFilter valueForKey:kCIOutputImageKey];
        CGImageRef cgImage = [ciContext createCGImage:result fromRect:[result extent]];
        UIImage *adjustedImage = [UIImage imageWithCGImage:cgImage];
        CGImageRelease(cgImage);
        
        
     
//        CGImageRef cgImage =
//        [ciContext createCGImage:[ciFilter outputImage] fromRect:[[ciFilter outputImage] extent]];
//        
//        // 文字解析対象の画像の色、コントラストを調整したものを変数に保存する
//        UIImage *adjustedImage = [UIImage imageWithCGImage:cgImage];
//    
//        CGImageRelease(cgImage);
        //        Tesseract *tesseract = [[Tesseract alloc]initWithDataPath:@"tessdata" language:kLanguage];
        
        Tesseract *tesseract = [[Tesseract alloc]initWithDataPath:@"tessdata" language:kLanguage];
//        [tesseract setLanguage:kLanguage];
   
        [tesseract setImage:adjustedImage]; //image to check
        [tesseract recognize];
        NSString *recognizedText = [tesseract recognizedText];
        tesseract = nil; //deallocate and free all memory

        dispatch_async(dispatch_get_main_queue(), ^{
            // 解析結果を画面に表示する
            [self updateUI:recognizedText];
            
//            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            imageView.image = adjustedImage;
            
        });
    });
    
}

- (void)updateUI:(NSString *)text
{
    // Update the text, stop animating the activity indicator,
    // and show the text view again
    contenLab.text = text;
  
    NSLog(@"结果为：\n%@",text);
}

//修改头像
- (void)changeHeadImage
{
    UIActionSheet *headImageSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", nil];
    headImageSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [headImageSheet showInView:self.view];
}

#pragma mark - actionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            [self takePhotos];
            
            break;
        case 1:
//            [self choosePicture];
            break;
        default:
            break;
    }
}

#pragma mark - 相册中选取



#pragma mark - 拍照

- (void)takePhotos
{
    
    [self customButtonTapped];
//    [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
//    [self getImage];
}


- (void)customButtonTapped
{
    // Check if the current device has a camera.
    if ([SACameraPickerViewController isCameraPickerViewControllerAvailable]) {
        // Setup the SACameraPickerViewController using the camera snapshot mode SACameraPickerViewControllerModeNormal.
        
        // Set the SACameraPickerViewController's Delegate
        imagePicker.delegate = self;
        
        // Optionally Set the Image Size
        imagePicker.previewSize = CGSizeMake(300, 80);
        
        // Present the SACameraPickerViewController's View.
        [self presentViewController:imagePicker animated:YES completion:nil];
    } else {
        NSLog(@"SACameraPickerViewController is not available, are you running this in the iPhone Simulator?");
    }
}

- (void)cameraPickerViewControllerDidCancel:(SACameraPickerViewController *)cameraPicker
{
    // Could do something here
}


// Required - The return info from the SACameraPickerViewController.
- (void)cameraPickerViewController:(SACameraPickerViewController *)cameraPicker didTakeImageWithInfo:(NSDictionary *)info
{
    // Fetch the UIImage from the info dictionary
    UIImage *image = [info objectForKey:SACameraPickerViewControllerImageKey];
    
    // Set the example UIImageView's image to the output UIImage.
    imageView.image = image;
    [self analyze:image];
   
   
}

//- (void)choosePicture
//{
//    [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
//    
//    [self getImage];
//}


- (void)getImage
{
    // Set the delegate to self so we get notified when the image has been chosen
    [imagePicker setDelegate:self];
    
    // Present the UIImagePickerController
    [self presentViewController:imagePicker animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    
    [picker dismissViewControllerAnimated:NO completion:^() {
        // Get the image that was chosen (the edited image
        UIImage *portraitImg = [info objectForKey:UIImagePickerControllerEditedImage];
        
        // Display the image on the screen
        imageView.image = portraitImg;
        [self analyze:portraitImg];
        
//        portraitImg = [self imageByScalingToMaxSize:portraitImg];
//        // 裁剪
//        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, 60) limitScaleRatio:3.0];
//        imgEditorVC.delegate = self;
//        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
            
            
            
//        }];
    }];

    
       // Start processing the image in the background
    
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        //        NSLog(@"could not scale image");
        
        //pop the context to get back to the default
        UIGraphicsEndImageContext();
    return newImage;
}


#pragma mark VPImageCropperDelegate(获得截取图片)
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {

    imageView.image = editedImage;
    [self performSelectorInBackground:@selector(analyze:) withObject:editedImage];
    
    [self dismissViewControllerAnimated:YES completion:nil];

    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
